package com.qingfeng.client.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qingfeng.base.model.Page;
import com.qingfeng.client.VO.GoodsAddVo;
import com.qingfeng.client.VO.GoodsQueryVo;
import com.qingfeng.client.VO.GoodsRecommendVo;
import com.qingfeng.client.VO.GoodsStatVo;
import com.qingfeng.client.bean.*;
import com.qingfeng.client.dao.GoodsCommonMapper;
import com.qingfeng.client.dao.GoodsMapper;
import com.qingfeng.client.dao.GrandMapper;
import com.qingfeng.client.service.GoodsService;
import com.qingfeng.client.service.GoodsTypeService;
import com.qingfeng.client.util.PingYing;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = "商品接口")
@RestController
@RequestMapping(value = "/api/goods")
public class GoodsApi extends BaseV1Api {

    @Resource
    private GoodsService goodsService;

    @Resource
    private GoodsCommonMapper goodsCommonDao;

    @Resource
    private GoodsTypeService goodsTypeService;


    @Resource
    private GrandMapper grandMapper;

    @Resource
    private GoodsMapper goodsMapper;

    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());


    @ApiOperation("更新上下架状态")
    @PostMapping(value = "/updateStat")
    public Object updateStat(@RequestBody GoodsStatVo goodsStatVo){
        Seller seller = getUser();
        GoodsCommon goodsCommon = goodsCommonDao.selectById(goodsStatVo.getId());
        if (goodsCommon.getStoreId().equals(seller.getStoreId())){
            if (goodsStatVo.getSellStat()<0){
                if (goodsCommon.getRecommend()!=null && goodsCommon.getRecommend()==1){
                    return error("请先关闭热销，再下架");
                }
            }
            goodsCommon.setSellStat(goodsStatVo.getSellStat());
            goodsCommon.setUpdateTime((int) System.currentTimeMillis());
            goodsCommonDao.updateById(goodsCommon);
        }else {
            return error("当前用户无该商品");
        }
        if (goodsStatVo.getSellStat()==1){
            return success("上架成功");
        }else {
            return success("下架成功");
        }

    }


    @ApiOperation("设置首页推荐")
    @PostMapping(value = "/updateRecommend")
    public Object updateRecommend(@RequestBody GoodsRecommendVo goodsRecommendVo){
        Seller seller = getUser();
        GoodsCommon goodsCommon = goodsCommonDao.selectById(goodsRecommendVo.getId());
        if (goodsCommon.getStoreId().equals(seller.getStoreId())){
            if (goodsRecommendVo.getRecommend()>0){
                if (goodsCommon.getSellStat()==null || goodsCommon.getSellStat()==-1){
                    return error("该商品已经停售，无法上推荐");
                }
            }
            goodsCommon.setRecommend(goodsRecommendVo.getRecommend());
            goodsCommon.setUpdateTime((int) System.currentTimeMillis());
            goodsCommonDao.updateById(goodsCommon);
        }else {
            return error("当前用户无该商品");
        }
        if (goodsRecommendVo.getRecommend()==1){
            return success("加入热销成功");
        }else {
            return success("退出热销成功");
        }
    }

    @ApiOperation("商品排序")
    @GetMapping(value = "/{id}/sort/{sort}")
    public Object goodsSort(
            @ApiParam(name = "商品id",value="90",required = true)@PathVariable("id") long id,
            @ApiParam(name = "排序序号",value="1",required = true)@PathVariable("sort")long sort){
        Seller seller = getUser();
        GoodsCommon goodsCommon = goodsCommonDao.selectById(id);
        if (goodsCommon.getStoreId().equals(seller.getStoreId())){
            goodsCommon.setSort(sort);
            goodsCommonDao.updateById(goodsCommon);
        }else {
            return error("当前用户无该商品");
        }
        return success("修改成功");
    }


    /**
     * 新增一个商品，并且可添加多个物品
     * @param goodsAddVo 传入的参数
     * @return 添加商品的结果
     */
    @ApiOperation("新增商品")
    @PostMapping(value = "/add")
    public Object add(@RequestBody GoodsAddVo goodsAddVo) {
        Seller seller = getUser();
        GoodsCommon goodsCommon = goodsAddVo.getGoodsCommon();
        List list = goodsCommonDao.selectByNameAndStoreId(goodsCommon.getName(),seller.getStoreId());
        if (list.size()>0){
            return error("商品名字已存在");
        }

        String py = PingYing.getAllFirstLetter(goodsCommon.getName());
        goodsCommon.setNamePy(py);
        goodsCommon.setStoreId(seller.getStoreId());
        goodsCommon.setSellStat(1);
        goodsCommon.setSort(0L);

        List<Goods> goodsBeans = goodsAddVo.getGoods();
        if (goodsService.add(goodsCommon, goodsBeans)) {
            return success(null);
        } else {
            return error("未知异常，请联系管理员");
        }
    }




    @ApiOperation("商品查询")
    @PostMapping(value = "/list")
    public Object queryByStore(@RequestBody JSONObject jsonObject) {
        GoodsQueryVo goodsQueryVo = JSON.toJavaObject(jsonObject.getJSONObject("condition"), GoodsQueryVo.class);
        Page page = parsePageJSON(jsonObject.getJSONObject("page"));
        Seller Seller = getUser();
        Integer storeId = Seller.getStoreId();
        if (storeId == null) {
            return error(null);
        }
        goodsQueryVo.setStoreId(storeId);
        Page page1 = (Page) goodsService.queryByStore(page, goodsQueryVo);
        List list = page1.getRecords();
        if (list != null) {
            return successPage(page1);
        } else {
            return error(null);
        }
    }



    /**
     * 获取商品的详细属性
     */
    @ApiOperation("获取商品的详细属性")
    @GetMapping(value = "/getGoodsInfo/{id}")
    public Object getGoodsInfo(@PathVariable(value = "id") Long id, HttpSession session) {
        Seller Seller = getUser();
        List goodsBeans = goodsService.getGoodsInfo(id);
        //返回所有类别名字和对应的id
        List<GoodsType> type = goodsTypeService.getType();
        int typeId = goodsService.getCategory(id);
        GoodsCommon goodsCommon = goodsCommonDao.selectById(id);
        Grand grand = grandMapper.selectById(goodsCommon.getGrandId());

        Map map = new HashMap();
        map.put("type",type);
        map.put("list",goodsBeans);
        map.put("typeId",typeId);
        map.put("goodsCommon",goodsCommon);
        map.put("grand",grand);

        List norms = goodsService.fanXian(id);
        if (goodsBeans == null) {
            return error(null);
        } else {
            //@todo 废弃guige字段，使用attrs
            map.put("guiGe",norms);
            map.put("attrs",goodsMapper.getAttrsByGoodsCommonId(id));
            return success(map);
        }
    }


    /**
     * 更新多个物品的信息
     */
    @ApiOperation("更新多个物品的信息")
    @PostMapping(value = "/updateGoods")
    public Object updateGoods(@RequestBody JSONObject jsonObject) {
        GoodsCommon GoodsCommon = JSON.parseObject(jsonObject.get("goodsCommon").toString(), GoodsCommon.class);
        List<Goods> goodsBeans = JSONArray.parseArray(jsonObject.getJSONArray("goods").toString(), Goods.class);
        if (goodsService.updateGoods(goodsBeans) && goodsService.updateGoodsCommon(GoodsCommon)) {
            return success(null);
        } else {
            return error(null);
        }
    }


    /**
     * @todo 废弃，将来需要删除
     * @param vo
     * @return
     */
    @ApiOperation("商品更新")
    @RequestMapping(value = "/update")
    @Transactional
    public Object update(@RequestBody GoodsUpdateVo vo) {

        // 更新已有的属性,Goods2attrsBean
        List<Goods2attrs> updateAttrs = vo.getUpdateAttrs();
        if (updateAttrs != null && updateAttrs.size() >= 0) {
            goodsService.updateValueByValueId(updateAttrs);
        }

        //修改商品基本属性,GoodsCommon里面的基本属性:商品名称...
        goodsService.updateGoodsCommon(vo.getGoodsCommon());

        // 新增商品属性和对应商品
        List<Goods> goods = vo.getGoods();
        goodsService.updateGoods2(goods, vo.getGoodsCommon().getId());
        return success("更新成功");
    }


    /**
     * @todo 以后使用

     * @param vo
     * @return
     */
    @ApiOperation("商品更新2")
    @RequestMapping(value = "/update2")
    @Transactional
    public Object update2(@RequestBody GoodsUpdateVo vo) {
        //修改商品基本属性,GoodsCommon里面的基本属性:商品名称...
        goodsService.update(vo);
        return success("更新成功");
    }



    /**
     * 商品规格的上下架
     *
     * @param jsonObject
     * @return
     */
    @ApiOperation("商品规格的上下架")
    @PostMapping(value = "/updateState")
    public Object updateState(@RequestBody JSONObject jsonObject) {
        if (goodsService.updateState(jsonObject)) {
            return success("下架成功");
        }
        return error("下架失败");
    }


    @ApiOperation("所以商品查询")
    @PostMapping(value = "/listAll")
    public Object queryAllByStore(@RequestBody JSONObject jsonObject) {
        GoodsQueryVo goodsQueryVo = JSON.toJavaObject(jsonObject.getJSONObject("condition"), GoodsQueryVo.class);
        Seller Seller = getUser();
        Integer storeId = Seller.getStoreId();
        if (storeId == null) {
            return error(null);
        }
        goodsQueryVo.setStoreId(storeId);
        List list = goodsService.queryAllByStore(goodsQueryVo);
        if (list != null) {
            return success(list);
        } else {
            return error(null);
        }
    }


}
